#!usr/bin/python
# encoding=utf-8

'''
Created on Apr 2, 2014

@author: root
'''

import socket
import simplejson
import time
import uuid
from datetime import datetime
from wm.etc.config import ALARMTYPE
from wm.lib import monitorlib,wmalert
from wm.etc.config import SOCKET
from wm.lib.loglib import log_info,log_error
from wm.db.TransactionManager import TransactionManager

def tcp_connect_check(host,port,count=SOCKET['COUNT']):
    '''
    @Tcp 连接检测 | hostSocket 已经存在同类函数
    '''
                        
    for i in xrange(count):
        sock = socket.socket()
        sock.settimeout(SOCKET['FPROTIMEOUT'])
        try:        
            start = datetime.now()
            sock.connect((host, int(port)))
            sock.send('PORT_IS_ALIVE')        
            end = datetime.now()
        except Exception as e:
            log_info("tcp连接失败:"+str(e))
            print "tcp连接失败:"+str(e)
            time.sleep(SOCKET['INTERVAL'])
            continue
        responsetime = (end - start).microseconds / 1000
        return True ,simplejson.dumps({"responsetime":responsetime})
    return False ,simplejson.dumps({"responstime":0})
    

def tcp_check_alarm(url, tcpport,row):
    print url
    try:
        sql = None
        ret = tcp_connect_check(url,int(tcpport))
        tran = TransactionManager()
        try:
            tran.startTransaction()
            if ret[0] == False:
                alarmcontent = 'TCP port:'+str(tcpport)
                alarmid = uuid.uuid1().__str__().replace("-","") 
                sql = "insert into alarmevent("+\
                             "id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,"+\
                                    "status,websiteName,websiteConfigInfo_id) "+\
                                    "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                                    "'4'" + ",'" + alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + row[2] + "'," +\
                                    "'" + row[0] + "')"      
                tran.execute(sql)
                monitorlib.update_recent_alarmevent(tran,row[0],row[2],'4',alarmcontent)
                wmalert.website_alert(alarm_type=ALARMTYPE['PORT_STATUS_ALARM'],websiteid=row[0],
                                      websitename=row[2],url=row[1],content=alarmcontent)  
                  
                sql = "insert into portavailablity("+\
                                 "id,createDate,modifyDate,port,portStatus,portType,alarmEvent_id,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(tcpport) + "','" + str(0) + "',"+"0" + ",'" + str(alarmid) + "','" + row[0] + "')"    
            else:
                sql = "insert into portavailablity("+\
                                 "id,createDate,modifyDate,port,portStatus,portType,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(tcpport) + "','" + str(1) + "'," + "0" +",'" + row[0] + "')"
            tran.execute(sql)
            tran.commitTransaction()
        except:
            print 'tcp rollbackTransaction'
            tran.rollbackTransaction()
        finally:
            tran.close()  
    except Exception as e:
        log_error("tcp_check_alarm():"+str(e))
        print "tcp_check_alarm():",str(e)
    
if __name__ == '__main__':
    '''
    @test
    '''
    ret = tcp_connect_check('wwww.baidu.com',80)
    print ret[0]
